package edu.erepbot.data.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataService {
	
	private static final Logger log = LoggerFactory.getLogger(DataService.class);
	private static EntityManager em = null;
	private static EntityManagerFactory emf = null;
	private static DataService INSTANCE;

	private DataService(){
		if(emf == null)
			emf = Persistence.createEntityManagerFactory("erepbot");

		if(em == null)
			em = emf.createEntityManager();
	}
	
	private DataService getInstance(){
		if(INSTANCE == null)
			INSTANCE = new DataService();
		return INSTANCE;
	}
	
	public EntityManager getEm(){
		return em;
	}
	
	public void txBegin(){
		if(em.getTransaction().isActive()){
			log.info("Joining transaction.");
		} else {
			em.getTransaction().begin();
			log.info("txBegin");
		}		
	}
	
	public void txCommit(){
		if(em.getTransaction().isActive()){
			em.getTransaction().commit();
			log.info("txCommit");
		} else {
			log.info("Transaction is not active");
		}
			
	}
	
	public void txRollback(){
		if(em.getTransaction().isActive()){
			em.getTransaction().rollback();
			log.info("txRollback");
		} else {
			log.info("Transaction is not active");
		}
	}

}
